/*
 ============================================================================
 Name		: M3UFileGenerater.cpp
 Author	  : JohnLZeng
 Version	 : 1.0
 Copyright   : Your copyright notice
 Description : CM3UFileGenerater implementation
 ============================================================================
 */

#include "M3UFileGenerater.h"

#include "SHPlatForm.h"
#include "EngineDef.h"
#include "CommonFileUtil.h"
#include "CommonUtils.h"

CM3UFileGenerater::CM3UFileGenerater()
	{
	// No implementation required
	}

CM3UFileGenerater::~CM3UFileGenerater()
	{
	}

CM3UFileGenerater* CM3UFileGenerater::NewLC()
	{
	CM3UFileGenerater* self = new (ELeave) CM3UFileGenerater();
	CleanupStack::PushL(self);
	self->ConstructL();
	return self;
	}

CM3UFileGenerater* CM3UFileGenerater::NewL()
	{
	CM3UFileGenerater* self = CM3UFileGenerater::NewLC();
	CleanupStack::Pop(); // self;
	return self;
	}

void CM3UFileGenerater::ConstructL()
	{

	}
_LIT8(KM3UHeader,	"#EXTM3U\n");
_LIT8(KM3UINF, 		"#EXTINF:0,");
_LIT8(KLineBreak,	"\n");
TBool CM3UFileGenerater::Generate()
	{
	ArrayDocList* list = SHModel()->GetDocList();
	TInt count = list->Count();

	if (count == 0)
		return EFalse;

	TFileName filename;
	CCommonFileUtil::GetM3UFileEFirst(filename);
	
	TFileName path;
	CCommonFileUtil::GetDetailFolderEFirst(path);
	
	int pos = filename.LocateReverse('\\');
	if (pos != KErrNotFound)
		{
		TPtrC dirName = filename.Left(pos + 1);
		CCoeEnv::Static()->FsSession().MkDirAll(dirName);
		}

	RFile file;

	TInt err = file.Replace(CCoeEnv::Static()->FsSession(), filename,
			EFileWrite);
	if (KErrNone != err)
		{
		return EFalse;
		}

	CleanupClosePushL(file);

	file.Write(KM3UHeader);

	HBufC8* path8;
	path8 = CCommonUtils::ConvertToUTF8FromUnicode(path);
	for (TInt i = 0; i < count; i++)
		{
		CRSSBriefData* brief = (*list)[i];
		TPtrC name = brief->GetMp3File()->Des();
		HBufC8* name8 = CCommonUtils::ConvertToUTF8FromUnicode(name); 
		file.Write(KM3UINF);
		file.Write(name8->Des());
		file.Write(KLineBreak);
		file.Write(path8->Des());
		file.Write(name8->Des());
		file.Write(KLineBreak);
		file.Write(KLineBreak);
		delete name8;
		}
	delete path8;
	CleanupStack::PopAndDestroy(); // file
	return count == 0 ? EFalse : ETrue;
	}
